<?php

namespace App\Admin\Controllers;

use App\Miya\Models\BannerGroup;
use App\Miya\Tools\TagTool;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Validation\Rule;
use Overtrue\Pinyin\Pinyin;

class BannerGroupController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Banner管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new BannerGroup());
        $grid->model()->with('banners');

        $grid->column('id', '序号');
        $grid->column('name', 'Banner')->editable();
        $grid->column('tag', '标签')->label();
        $grid->column('image_list', '图片')->display(function () {
            $data['model'] = $this;
            return view('miya::banner_groups._image_list', $data);
        });

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new BannerGroup());

        $form->tab('基础设置', function (Form $form) {
            $form->text('name', '名称')->rules(['required']);
            $form->hasMany('banners', 'Banner图', function (Form\NestedForm $form) {
                $form->image('image', '图片')->uniqueName()->removable()
                    ->move(getMovePath('banners'));
                $form->text('title', '图片文本');
                $form->url('url', '图片超链接');
                $form->slider('rank', '排序')->options([
                    'max' => 100,
                    'min' => 1,
                    'step' => 1,
                ]);
            });
        })->tab('高级设置', function (Form $form) {
            if ($form->isCreating()) {
                $form->text('tag', '标签')->rules([Rule::unique('banner_groups')]);
            } elseif ($form->isEditing()) {
                $model = BannerGroup::find(request()->route('banner_group'));
                $form->text('tag', '标签')
                    ->rules([Rule::unique('banner_groups')->ignore($model)]);
            }
        });

        $form->saving(function (Form $form) {
            if ($form->name && !$form->tag) {
                $form->tag = TagTool::makeTag($form->name, config('miya.tag_suffix.banner'));
            }
        });
        return $form;
    }
}
